Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Text
Imports System.Collections.Generic
Imports ASPNET.StarterKit.BusinessLogicLayer

Partial Public Class Project_Details_aspx
    Inherits System.Web.UI.Page

    Private CurrentProject As Project = Nothing

    Private Sub GetCurrentProject()

        Dim projectIdFromQueryString As Integer
        If Not Request.QueryString("ProjectId") Is Nothing AndAlso Int32.TryParse(CStr(Request.QueryString("ProjectId")), projectIdFromQueryString) Then
            CurrentProject = Project.GetProjectById(projectIdFromQueryString)
        End If

    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

        GetCurrentProject()
        If (Not Page.IsPostBack) Then

            ManagerData.SelectParameters.Add(New Parameter("roleName", TypeCode.String, "ProjectManager"))
            ProjectConsultantData.SelectParameters.Add(New Parameter("roleName", TypeCode.String, "Consultant"))

            If Not CurrentProject Is Nothing Then

                ProjectName.Text = CurrentProject.Name
                Dim dt As DateTime = Convert.ToDateTime(CurrentProject.CompletionDate)
                CompletionDate.Text = dt.ToString("d")
                Duration.Text = Convert.ToString(CurrentProject.EstimateDuration)
                Description.Text = CurrentProject.Description
                Managers.SelectedValue = CurrentProject.ManagerUserName

                Consultants.DataBind()
                ProjectCategoryColumn.Visible = True
            Else
                ProjectCategoryColumn.Visible = False
            End If

            If (Page.User.IsInRole("ProjectAdministrator")) Then
                ProjectData.SelectMethod = "GetAllProjects"
            Else
                ProjectData.SelectParameters.Add(New Parameter("userName", TypeCode.String, Page.User.Identity.Name))
                ProjectData.SelectMethod = "GetProjectsByManagerUserName"
                ProjectData.SortParameterName = "sortParameter"
            End If

        End If

        DeleteButton2.Attributes.Add("onclick", "return confirm('Deleting a project will also delete all the time entries and categories associated with the project. This deletion cannot be undone. Are you sure you want to delete this project?')")

    End Sub

    Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As EventArgs) Handles Me.LoadComplete

        If Not CurrentProject Is Nothing Then
            SelectProjectMembers(CurrentProject.Id)
        End If

    End Sub

    Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs) Handles Me.PreRender

        ViewState("ActiveConsultants") = BuildValueList(Consultants.Items, True)

    End Sub

    Protected Sub AddButton_Click(ByVal obj As Object, ByVal args As EventArgs) Handles AddButton.Click

        If Page.IsValid = False Then
            Return
        End If

        If Not CurrentProject Is Nothing Then
            Dim wasCategorySave As Boolean = False

            Dim newCategory As Category = New Category(Abbrev.Text, Convert.ToDecimal(CatDuration.Text), CategoryName.Text, CurrentProject.Id)
            wasCategorySave = newCategory.Save()
            ListAllCategories.DataBind()
        End If

    End Sub

    Protected Function BuildValueList(ByVal items As ListItemCollection, ByVal itemMustBeSelected As Boolean) As String

        Dim idList As StringBuilder = New StringBuilder()
        For Each item As ListItem In items
            If itemMustBeSelected AndAlso (Not item.Selected) Then
                Continue For
            Else
                idList.Append(item.Value.ToString())
                idList.Append(",")
            End If
        Next item

        Return idList.ToString()

    End Function

    Protected Sub CancelButton_Click(ByVal obj As Object, ByVal args As EventArgs) Handles CancelButton2.Click

        Response.Redirect("Project_List.aspx")

    End Sub

    Protected Sub CopyButton_Click(ByVal obj As Object, ByVal args As EventArgs) Handles CopyButton.Click

        If Not CurrentProject Is Nothing Then

            Dim selectedProjectId As Integer = Convert.ToInt32(ProjectList.SelectedValue)
            Dim newCategories As List(Of Category) = Category.GetCategoriesByProjectId(selectedProjectId)

            For Each cat As Category In newCategories
                Dim newCat As Category = New Category(cat.Abbreviation, cat.EstimateDuration, cat.Name, CurrentProject.Id)
                newCat.Save()
            Next cat

            CategoryData.DataBind()
            ListAllCategories.DataBind()

        End If

    End Sub

    Protected Sub DeleteButton_Click(ByVal obj As Object, ByVal args As EventArgs) Handles DeleteButton2.Click

        If Not CurrentProject Is Nothing Then
            Dim newProject As Project = Project.GetProjectById(CurrentProject.Id)
            newProject.Delete()
            Response.Redirect("Project_List.aspx")
        End If

    End Sub

    Protected Sub SaveButton_Click(ByVal obj As Object, ByVal args As EventArgs) Handles SaveButton2.Click

        If Page.IsValid = False Then
            Return
        End If

        Dim newProject As Project

        If Not CurrentProject Is Nothing Then
            newProject = Project.GetProjectById(CurrentProject.Id)

        Else
            newProject = New Project(Page.User.Identity.Name, Page.User.Identity.Name, ProjectName.Text)
        End If

        newProject.Name = ProjectName.Text
        newProject.CompletionDate = Convert.ToDateTime(CompletionDate.Text)
        newProject.Description = Description.Text
        newProject.EstimateDuration = Convert.ToDecimal(Duration.Text)
        newProject.ManagerUserName = Managers.SelectedItem.Value

        If (Not newProject.Save()) Then
            ErrorMessage.Text = "There was an error.  Please fix it and try it again."
        End If

        UpdateProjectMembers(newProject.Id)
        Dim strUrl As String = "Project_Details.aspx?ProjectId=" & newProject.Id.ToString()
        Response.Redirect(strUrl)

    End Sub

    Protected Sub SelectProjectMembers(ByVal projectId As Integer)

        Consultants.DataBind()
        Dim userList As List(Of String) = Project.GetProjectMembers(projectId)

        For Each user As String In userList
            Dim item As ListItem = Consultants.Items.FindByValue(user)
            item.Selected = True
        Next user

    End Sub

    Protected Sub UpdateProjectMembers(ByVal projectId As Integer)

        Dim activeConsultants As String = String.Empty

        If Not ViewState("ActiveConsultants") Is Nothing Then
            activeConsultants = ViewState("ActiveConsultants").ToString()
        End If

        For Each item As ListItem In Consultants.Items
            If item.Selected Then
                If (Not activeConsultants.Contains(item.Value & ",")) Then
                    Project.AddUserToProject(projectId, item.Text)
                End If
            Else
                If activeConsultants.Contains(item.Value & ",") Then
                    Project.RemoveUserFromProject(projectId, item.Text)
                End If
            End If
        Next item

    End Sub

    Protected Sub ProjectList_PreRender(ByVal sender As Object, ByVal e As EventArgs) Handles ProjectList.PreRender

        Dim item As ListItem = ProjectList.Items.FindByText(ProjectName.Text)
        If Not item Is Nothing Then
            ProjectList.Items.Remove(item)
        End If

        If ProjectList.Items.Count = 0 Then
            ProjectList.Enabled = False
        End If

    End Sub

    Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs) Handles CustomValidator1.ServerValidate

        If Description.Text.Length > 200 Then
            args.IsValid = False
        Else
            args.IsValid = True
        End If

    End Sub

End Class
